package com.yaha.controler.utils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.yaha.controler.devices.interfaces.WifiScanListener;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.text.TextUtils;
import android.util.Log;

/**
 * <功能描述>wifi连接管理工具类
 * 
 * @author Frewen.W/909091
 * @version [版本号, 2015-4-7]
 * @since [产品/模块版本]
 */
public class WifiUtil {
	private static final String TAG = "WifiUtil";

	/** 定义WifiManager对象 */
	private WifiManager mWifiManager;
	/** 定义WifiInfo对象 */
	private WifiInfo mWifiInfo;
	/** 扫描出的网络连接列表 */
	private List<ScanResult> mWifiList;
	/** 网络连接列表 */
	private List<WifiConfiguration> mWifiConfiguration;
	/** 定义WifiLock */
	private WifiLock mWifiLock;

	private Context mContext;
	private WifiReceiver mWifiReceiver;

	public WifiUtil(Context context) {
		mContext = context;
		mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		mWifiInfo = mWifiManager.getConnectionInfo();
		mWifiReceiver = new WifiReceiver();
	}

	/**
	 * <功能描述>注销广播接收者
	 */
	public void release() {
		mContext.unregisterReceiver(mWifiReceiver);
	}

	/**
	 * 打开WIFI
	 */
	public void openWifi() {
		if (!mWifiManager.isWifiEnabled()) {
			mWifiManager.setWifiEnabled(true);
		}
	}

	/**
	 * 关闭WIFI
	 */
	public void closeWifi() {
		if (mWifiManager.isWifiEnabled()) {
			mWifiManager.setWifiEnabled(false);
		}
	}

	/**
	 * 当前WIFI状态
	 */
	public int checkState() {
		return mWifiManager.getWifiState();
	}

	/**
	 * 锁定WifiLock
	 */
	public void acquireWifiLock() {
		mWifiLock.acquire();
	}

	/**
	 * 解锁WifiLock
	 */
	public void releaseWifiLock() {
		// 判断时??锁定，这个地方不是很清楚
		if (mWifiLock.isHeld()) {
			mWifiLock.acquire();
		}
	}

	/**
	 * 创建WifiLock
	 */
	public void creatWifiLock() {
		mWifiLock = mWifiManager.createWifiLock("Test");
	}

	/**
	 * 得到配置好的网络
	 * 
	 * @return
	 */
	public List<WifiConfiguration> getConfiguration() {
		mWifiConfiguration = mWifiManager.getConfiguredNetworks();
		return mWifiConfiguration;
	}

	/**
	 * 指定配置好的网络进行连接
	 * 
	 * @param index
	 */
	public void connectConfiguration(int index) {
		// 索引大于配置好的网络索引返回
		if (index > mWifiConfiguration.size()) {
			return;
		}
		// 连接配置好的指定ID的网??
		mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true);
	}

	/**
	 * 开始搜索
	 */
	public void startScan() {
		mWifiManager.startScan();
		// 得到扫描结果
		mWifiList = mWifiManager.getScanResults();
		// 得到配置好的网络连接
		mWifiConfiguration = mWifiManager.getConfiguredNetworks();
		mContext.registerReceiver(mWifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
	}

	/**
	 * 得到网络列表
	 * 
	 * @return
	 */
	public List<ScanResult> getWifiList() {
		return mWifiList;
	}

	/**
	 * 查看扫描结果
	 * 
	 * @return
	 */
	public StringBuilder lookUpScan() {
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < mWifiList.size(); i++) {
			stringBuilder.append("Index_" + new Integer(i + 1).toString() + ":");
			// 将ScanResult信息转换成一个字符串??
			// 其中把包括：BSSID、SSID、capabilities、frequency、level
			stringBuilder.append((mWifiList.get(i)).toString());
			stringBuilder.append("/n");
		}
		return stringBuilder;
	}

	/**
	 * 得到MAC地址
	 * 
	 * @return
	 */
	public String getMacAddress() {
		return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
	}

	/**
	 * 得到接入点的BSSID
	 * 
	 * @return
	 */
	public String getBSSID() {
		return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
	}

	/**
	 * 得到IP地址
	 * 
	 * @return
	 */
	public int getIPAddress() {
		return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
	}

	/**
	 * 得到连接的ID
	 * 
	 * @return
	 */
	public int getNetworkId() {
		return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
	}

	/**
	 * 得到WifiInfo的所有信息包
	 * 
	 * @return String
	 */
	public String getWifiInfo() {
		return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
	}

	/**
	 * 添加????网络并连??
	 * 
	 * @param WifiConfiguration
	 */
	public boolean addNetwork(WifiConfiguration wcg) {
		// add by zyc
		/*
		 * if (MyApplication.MIRCASTSTATE_CON == MyApplication.wfdApState){ //
		 * 如果投投看连接中，先断开投投看再切换网络
		 * MyApplication.toutoukanFragment.disconnectWfdAp(); Log.e(TAG,
		 * "[addNetwork] disconnect miracast..."); try { Thread.sleep(200); }
		 * catch (InterruptedException e) { e.printStackTrace(); } }
		 */
		WifiInfo wi = mWifiManager.getConnectionInfo();
		if (wi != null) {
			mWifiManager.disableNetwork(wi.getNetworkId());
		}

		int wcgID = mWifiManager.addNetwork(wcg);
		boolean b = mWifiManager.enableNetwork(wcgID, true);

		mWifiManager.updateNetwork(wcg);
		mWifiManager.saveConfiguration();

		Log.d(TAG, "wcgID=" + wcgID);
		Log.d(TAG, "b=" + b);
		return b;
	}

	/**
	 * 断开指定ID的网??
	 * 
	 * @param int
	 */
	public void disconnectWifi(int netId) {
		mWifiManager.disableNetwork(netId);
		mWifiManager.disconnect();
	}

	/**
	 * 然后是一个实际应用方法，只验证过没有密码的情况：
	 * 
	 * @param String
	 *            SSID
	 * @param String
	 *            Password
	 * @param int Type
	 * @return WifiConfiguration
	 */
	public WifiConfiguration CreateWifiInfo(String SSID, String Password, int Type) {
		WifiConfiguration config = new WifiConfiguration();
		config.allowedAuthAlgorithms.clear();
		config.allowedGroupCiphers.clear();
		config.allowedKeyManagement.clear();
		config.allowedPairwiseCiphers.clear();
		config.allowedProtocols.clear();
		config.SSID = "\"" + SSID + "\"";

		WifiConfiguration tempConfig = this.IsExsits(SSID);
		if (tempConfig != null) {
			mWifiManager.removeNetwork(tempConfig.networkId);
		}

		if (Type == 1) // WIFICIPHER_NOPASS
		{
			// config.wepKeys[0] = "";
			config.wepKeys[0] = null;
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
			config.wepTxKeyIndex = 0;
		}
		if (Type == 2) // WIFICIPHER_WEP
		{
			config.hiddenSSID = true;
			config.wepKeys[0] = "\"" + Password + "\"";
			config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
			config.wepTxKeyIndex = 0;
		}
		if (Type == 3) // WIFICIPHER_WPA
		{
			config.preSharedKey = "\"" + Password + "\"";
			config.hiddenSSID = true;
			config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
			config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
			// config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
			config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
			config.status = WifiConfiguration.Status.ENABLED;
		}
		return config;
	}

	/**
	 * 判断SSID是否在已配置列表
	 * 
	 * @param SSID
	 *            String
	 * @return WifiConfiguration
	 */
	public WifiConfiguration IsExsits(String SSID) {
		List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
		for (WifiConfiguration existingConfig : existingConfigs) {
			if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
				return existingConfig;
			}
		}
		return null;
	}

	/**
	 * 根据SSID获取扫描出的网络连接.
	 * 
	 * @param ssid
	 * @return 网络连接
	 */
	public ScanResult getScanResultBySsid(String ssid) {
		List<ScanResult> srList = getWifiList();
		ScanResult tempScanResult = null;

		if (null != srList && !srList.isEmpty()) {
			for (int i = 0; i < srList.size(); i++) {
				tempScanResult = srList.get(i);
				// Log.d(TAG, "getScanResultBySsid ---> ssid " +
				// tempScanResult.SSID);
				if (null != tempScanResult.SSID && tempScanResult.SSID.equals(ssid)) {
					break;
				} else {// add by yw 907595
					tempScanResult = null;
				}
			}
		}
		return tempScanResult;
	}

	/**
	 * 根据SSID获取扫描出的网络连接列表.
	 * 
	 * @param ssid
	 * @return 网络连接
	 */
	public List<ScanResult> getScanResultListBySsid(String ssid) {
		List<ScanResult> srList = getWifiList();
		List<ScanResult> tempList = new ArrayList<ScanResult>();
		ScanResult tempScanResult = null;

		if (null != srList && !srList.isEmpty()) {
			for (int i = 0; i < srList.size(); i++) {
				tempScanResult = srList.get(i);
				if (null != tempScanResult.SSID && tempScanResult.SSID.toLowerCase().contains(ssid)) {
					tempList.add(tempScanResult);
				}
				continue;
			}
		}
		return tempList;
	}

	/**
	 * 根据SSID获取扫描出不包含DONGLE的网络连接列
	 * 
	 * @param ssid
	 * @return 网络连接
	 */
	public List<ScanResult> getScanResultListExceptBySsid(String ssid) {
		List<ScanResult> srList = getWifiList();
		List<ScanResult> tempList = new ArrayList<ScanResult>();
		ScanResult tempScanResult = null;
		if (null != srList && !srList.isEmpty()) {
			for (int i = 0; i < srList.size(); i++) {
				tempScanResult = srList.get(i);
				if (null != tempScanResult.SSID && !tempScanResult.SSID.toLowerCase().contains(ssid)) {
					tempList.add(tempScanResult);
				}
				continue;
			}
		}
		return tempList;
	}

	/**
	 * 根据config移出wifi的config保存记录
	 * 
	 * @param wcg
	 */
	public void removeWifiConfiguration(WifiConfiguration wcg) {
		this.mWifiManager.removeNetwork(wcg.networkId);
		this.mWifiManager.saveConfiguration();
	}

	/**
	 * 根据SSID获取网络连接
	 * 
	 * @param ssid
	 * @return 网络连接
	 */
	public WifiConfiguration getWifiConfigurationBySsid(String ssid) {
		List<WifiConfiguration> wcList = getConfiguration();
		if (null != wcList && !wcList.isEmpty()) {
			for (WifiConfiguration existingConfig : wcList) {
				if (("\"" + ssid + "\"").indexOf(existingConfig.SSID) != -1) {
					return existingConfig;
				}
			}
		}
		/*
		 * WifiConfiguration tempConfiguration = null; if (null != wcList &&
		 * !wcList.isEmpty()) { for (int i = 0; i < wcList.size(); i++) {
		 * tempConfiguration = wcList.get(i); Log.i(TAG,
		 * "begin,tempConfiguration.SSID=" + tempConfiguration.SSID +" -> ssid="
		 * + ssid); Log.i(TAG, ""+ (null != tempConfiguration.SSID) +" && "+
		 * tempConfiguration.SSID.equals("\""+ssid+"\"")); if (null !=
		 * tempConfiguration.SSID &&
		 * tempConfiguration.SSID.toString().equals("\""+ssid+"\"")){ Log.i(TAG,
		 * "break,SSID=" + tempConfiguration.SSID +" -> ssid=" + ssid); break;
		 * }else{ tempConfiguration = null; } } }
		 */
		return null;
	}

	/**
	 * 获取网络信息.
	 * 
	 * @return
	 */
	public WifiInfo getmWifiInfo() {
		return mWifiInfo;
	}

	/**
	 * 设置网络信息.
	 * 
	 * @param mWifiInfo
	 */
	public void setmWifiInfo(WifiInfo mWifiInfo) {
		this.mWifiInfo = mWifiInfo;
	}

	public WifiManager getmWifiManager() {
		return mWifiManager;
	}

	public void setmWifiManager(WifiManager mWifiManager) {
		this.mWifiManager = mWifiManager;
	}

	public List<ScanResult> getmWifiList() {
		return mWifiList;
	}

	public void setmWifiList(List<ScanResult> mWifiList) {
		this.mWifiList = mWifiList;
	}

	public List<WifiConfiguration> getmWifiConfiguration() {
		return mWifiConfiguration;
	}

	public void setmWifiConfiguration(List<WifiConfiguration> mWifiConfiguration) {
		this.mWifiConfiguration = mWifiConfiguration;
	}

	/**
	 * 整数转ip格式
	 * 
	 * @param ip
	 * @return
	 */
	public String long2ip(long ip) {
		int[] b = new int[4];
		b[0] = (int) ((ip >> 24) & 0xff);
		b[1] = (int) ((ip >> 16) & 0xff);
		b[2] = (int) ((ip >> 8) & 0xff);
		b[3] = (int) (ip & 0xff);
		String x;
		x = Integer.toString(b[3]) + "." + Integer.toString(b[2]) + "." + Integer.toString(b[1]) + "."
				+ Integer.toString(b[0]);
		return x;
	}

	/**
	 * wifi信号强度4个级别
	 * 
	 * @return
	 */
	public static int level(int wifiLevel) {
		int SIGNAL_FULL = -50;
		int SIGNAL_LOW = -110;
		wifiLevel = (wifiLevel - SIGNAL_LOW) / ((SIGNAL_FULL - SIGNAL_LOW) / 5);
		if (wifiLevel > 4) {
			wifiLevel = 4;
		}
		if (wifiLevel < 1) {
			wifiLevel = 1;
		}
		return wifiLevel;
	}

	/**
	 * 因为不同手机通过getssid获取的值有的带有双引号，有的不带双引号，所以对于带引号的需要手动去掉
	 * 
	 * @param wifiInfo
	 * @return
	 */
	public static String getWifiInfoSSID(WifiInfo wifiInfo) {
		String s = wifiInfo.getSSID();
		Log.i(TAG, "wifiInfo:SSID=" + s);
		String s1 = null;
		String s2 = null;
		if (null != s && s.length() > 2) {
			s1 = s.substring(0, 1);
			s2 = s.substring(s.length() - 1, s.length());
			if ("\"".equals(s1) && "\"".equals(s2)) {
				s = s.substring(1, (s.length() - 1));
			}
		}
		Log.i(TAG, "wifiInfo:SSID=" + s);
		return s;
	}

	/**
	 * 是否支持5.8G true 支持2.4和5.8 false 支持2.4
	 * 
	 * @return
	 */
	public boolean IsDualBandSupported() {
		boolean flag = false;
		try {
			Method m = WifiManager.class.getMethod("isDualBandSupported");
			Object object = m.invoke(mWifiManager);
			Log.e(TAG, "object=" + object);
			flag = (Boolean) object;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * 创建wificonfig
	 * 
	 * @param ssid
	 * @param apPwd
	 * @param capabilities
	 *            加密类型：OPEN WEP WPA
	 * @return
	 */
	public WifiConfiguration createWifiConfiguration(String ssid, String apPwd, String capabilities) {
		WifiConfiguration config = null;
		// 判断是否需要密码
		if ("OPEN".equals(capabilities)) {
			config = CreateWifiInfo(ssid, "", 1);
		} else {
			if (!TextUtils.isEmpty(apPwd)) {
				if ("WEP".equals(capabilities)) {
					config = CreateWifiInfo(ssid, apPwd, 2);
				} else if ("WPA".equals(capabilities)) {
					config = CreateWifiInfo(ssid, apPwd, 3);
				}
			} else {
				// Toast.makeText(context, R.string.withoutpassword,
				// Toast.LENGTH_LONG).show();
			}
		}
		return config;
	}

	private final class WifiReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
				mWifiList = mWifiManager.getScanResults();
				if (null != mWifiScanListener) {
					mWifiScanListener.onWifiScanResultsChanged(mWifiList);
				}
			}
		}
	}

	private WifiScanListener mWifiScanListener;

	public void setWifiScanListener(WifiScanListener wifiScanListener) {
		mWifiScanListener = wifiScanListener;
	}

	public WifiScanListener getWifiScanListener() {
		return mWifiScanListener;
	}

	public void stopScan() {
		Log.d(TAG, "stopScan ---> ");
		mContext.unregisterReceiver(mWifiReceiver);
	}
}
